/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DataServices;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author DOANTUNGANH
 */
public class TableModel extends AbstractTableModel{
    
    // Name of column headers
    private Vector headers;
    
    // Data in table [][]
    private Vector data;

    // Constructor : set headers and data of the table from parameter ResultSet
    public TableModel(ResultSet rs) throws SQLException {
        
        // Metadata of rs, throws a SQLException if rs is not retrieved properly
        ResultSetMetaData rsMeta = rs.getMetaData();
        
        // Number of columns in the table
        int columnCount = rsMeta.getColumnCount();
        
        // Add headers to table
        headers = new Vector();
        for (int i = 1; i <= columnCount ; i++) {
            headers.addElement(rsMeta.getColumnName(i));
        }
        
        // Add data to table
        data = new Vector();
        while (rs.next()) {
            Vector dataRow = new Vector(columnCount);
            
            // Add data to row
            for (int i = 1; i <= columnCount; i++) {
                dataRow.addElement(rs.getObject(i));
            }
            
            // Add row to column
            data.addElement(dataRow);
        }
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public int getColumnCount() {
        return headers.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        
        // Get row data
        Vector rowData = (Vector) data.elementAt(rowIndex);
        
        // Get object
        return rowData.elementAt(columnIndex);
    }
    
    // Get headers name of a specific column
    public String getColumnName(int columnIndex){
        return (String) (headers.elementAt(columnIndex));
    }
    
}
